<?php
class Mageex_AdvanceSeo_Model_Old extends Mage_Core_Model_Abstract
{
	protected $_counter 		= 0;
	protected $_limitRecords 	= 0;
	
	//rewrite meta tag for product
	public function getAttributeArr($arrCode, $productId)
    {
		return Mage::helper('advanceseo/data')->getAttributeArr($arrCode, $productId);
    }
	
	public function rewriteMetaTag()
	{
		$modelProduct 		= Mage::getModel('catalog/product');
		$model 				= Mage::getModel('advanceseo/advanceseo');
		$advanceoSeoConllection = $model->getCollection()->addFieldToFilter('type', 'productid');
		
		$productCollection = Mage::getResourceModel('catalog/product_collection')
									->addAttributeToSelect('meta_title')
									->addAttributeToSelect('meta_description')
									->addAttributeToSelect('meta_keyword')
									->addFieldToFilter('visibility', array('eq'=>4));
									
		$advanceSeo = $advanceoSeoConllection->getFirstItem();			
		$advanceId 	= $advanceSeo->getId();
		$tagsId 	= $advanceSeo->getUrl();
			
		if($tagsId != NULL) {
			$productCollection->addFieldToFilter('entity_id', array('gt' => $tagsId));
		}
		
		if(Mage::helper('advanceseo/existeddata')->getSelectDateFrom() == 'C'){
			$strDate = Mage::helper('advanceseo/existeddata')->getDateFrom();
			$arrDate = array_reverse(explode('-', $strDate));
			$newDate = implode('-',$arrDate);
			$productCollection->addFieldToFilter('created_at', array('lt' => $newDate));
		}
		
		$productCollection->setPageSize((int)$this->_limitRecords);
		
		
		foreach($productCollection as $product){
		
			if($this->_counter == $this->_limitRecords){
				break;
			}
			$this->_counter++;
			
			//Rewrite meta
			$collection = Mage::getResourceModel('eav/entity_attribute_collection')
            				->setEntityTypeFilter( Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId() )
            				->addFilter("is_visible", 1)
            				->addFilter("is_filterable", 1);
							
			$arrCode = array();				
			foreach($collection->getItems() as $col) {
	            $arrCode[] = $col->getAttributeCode();
	        }
			
			$arrCode[] 	= 'name';
			$arrCode[] 	= 'computer_manufacturers';
			
			$attributeArr = $this->getAttributeArr($arrCode, $product->getId());
			$dataRewrite = array();
			if(Mage::helper('advanceseo/meta')->isEnableMetaTitle()){
				$title = '';
				$strTemplate = Mage::helper('advanceseo/meta')->getTemplateMetaTitle();
				if($strTemplate != ''){
					$arrTemplate = Mage::helper('advanceseo/data')->getArrFromTemplate($strTemplate);
					$title = Mage::helper('advanceseo/data')->getStrFromTemplate($arrTemplate, $attributeArr, $strTemplate);
				}	
				$dataRewrite['meta_title'] = $title;				
			}
			
			//Rewrite keyword
			if(Mage::helper('advanceseo/meta')->isEnableMetaKeyWord()){
				$strDescription = '';
				foreach($attributeArr as $key=>$value){
					if($key != 'price'){
						$strDescription	 .= ' ' . $value;
					}
				}
				
				$arrWord = Mage::helper('core/string')->splitWords($strDescription);
				
				if(count($arrWord>1)){
					$keyword = Mage::helper('advanceseo/data')->splitTwoWords($arrWord);
				}
				//Limit word title
				$limit 	= Mage::helper('advanceseo/meta')->getWordRangeTitle();
				
				$keyword 	= Mage::helper('advanceseo/data')->limitContentByWord($keyword, $limit);
				
				//Included Key Word
				$includedKeyWord = Mage::helper('advanceseo/meta')->getIncludedKeyWork();
				
				if(!empty($includedKeyWord)){
					$keyword .= ','. $includedKeyWord;
				}
				
				$dataRewrite['meta_keyword'] = $keyword ;
			}
			//Rewrite meta description
			if(Mage::helper('advanceseo/meta')->isEnableMetaDescription()){
				$arrCode[] = 'name';
				$arrCode[] = 'website';
				$arrCode[] = 'description';
				$arrCode[] = 'short_description';
				
				$desc	   = '';
            	$attributeArr = $this->getAttributeArr($arrCode, $product->getId());
            	$productMeta = Mage::helper('advanceseo/meta')->getTemplateMetaDescription();
				
            	$arrTemplate = Mage::helper('advanceseo/data')->getArrFromTemplate($productMeta);
            	$desc = Mage::helper('advanceseo/data')->getStrFromTemplate($arrTemplate, $attributeArr, $productMeta);
				//Limit description
				$limit 	= Mage::helper('advanceseo/data')->getWordRangeDescription();
				
				$desc		= Mage::helper('advanceseo/data')->limitContentByWord($desc, $limit);
				
				$dataRewrite['meta_description'] = $desc;
            }
			

			Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
			
			//save product meta information
			$modelProduct->load($product->getId())
						 ->setMetaKeyword($dataRewrite['meta_keyword'])
						 ->setMetaTitle($dataRewrite['meta_title'])
						 ->setMetaDescription($dataRewrite['meta_description'])
						 ->save();
			
			$dataView[] = $product->getId();	
			
		}
		//var_dump($dataView);
		
		$dataCore = array();
		$dataCore['type']= 'productid';
		$dataCore['url'] = max($dataView);
		
		
		if(count($advanceoSeoConllection) == 1){
			//$dataCore['url'] .= ',' . $tagsId;
			$model->load($advanceId)->addData($dataCore);
			$model->save();
		}else{	
			$model->setData($dataCore);
			$model->save();
		}
		
		
	}
	//rewrite url(review, tag)
	public function rewriteUrl()
	{
		//Rewrite tag
		$urlrewriteModel 	= Mage::getModel('core/url_rewrite');
        $dataRewrite 		= array();
		
		$model 				= Mage::getModel('advanceseo/advanceseo');
		
		if(Mage::helper('advanceseo/config')->isEnableRewriteTags()){
		
			$dataId				= array();
			$tagCollection 		= Mage::getModel('tag/tag')->getCollection();
			
			//If tags saved in advanceseo table
			$advanceoSeoConllection = $model->getCollection()->addFieldToFilter('type', 'tags');
			
			$advanceSeo = $advanceoSeoConllection->getFirstItem();			
			$advanceId 	= $advanceSeo->getId();
			$tagsId 	= $advanceSeo->getUrl();
				
			if($tagsId != NULL) {
				$tagCollection->addFieldToFilter('tag_id', array('gt' => $tagsId));
			}
			
			foreach ($tagCollection as $item) {
				
				$oldUrl 		= 'tag/product/list/tagId/'.$item->getId();
				$dataId[]		= $item->getId();			
				$requestPath 	= Mage::helper('advanceseo/config')->getPathTag().
														 '/'.
														 Mage::helper('advanceseo/data')->stringConvert($item->getName()).
														 Mage::helper('advanceseo/data')->getSuffix();
				//filter old target_path
				$rewriteCollection = $urlrewriteModel->getCollection()->addFieldToFilter('target_path', $oldUrl);
				$rewriteCollection->setPageSize((int)$this->_limitRecords);
				
				if($this->_counter == $this->_limitRecords){
					break;
				}
				
				if(count($rewriteCollection)==0){
					$dataRewrite['store_id'] = Mage::app()->getStore()->getId();
					$dataRewrite['id_path'] = Mage::helper('advanceseo/config')->getPathTag().'/'.$item->getId();
					$dataRewrite['target_path'] = $oldUrl;
					$dataRewrite['request_path'] = $requestPath; 
					//@ save url here
					$dataRewrite['is_system'] = 0;
					$urlrewriteModel->setData($dataRewrite);
					$urlrewriteModel->save();
					$this->_counter ++;
				}else{		 
					foreach($rewriteCollection as $rewrite){
							$idCoreUrl = $rewrite->getId();
							$requestPaths = $rewrite->getRequestPath();
							break;
					}
					if($requestPaths  != $requestPath){
							$data['request_path'] = $requestPath;
							$urlrewriteModel->load($idCoreUrl)->addData($data);
							$urlrewriteModel->setId($idCoreUrl)->save();
							$this->_counter ++;
					}
				}
				
			}
			$dataCore = array();
			$dataCore['type']='tags';
			$dataCore['url'] = max($dataId);
			if(count($advanceoSeoConllection) == 1){
				//$dataCore['url'] .= ',' . $tagsId;
				$model->load($advanceId)->addData($dataCore);
				$model->save();
			}else{	
				$model->setData($dataCore);
				$model->save();
			}
			unset($tagCollection);
		}
		
		 //Rewrite review
		 //Core_Url_Rewrite table
		if(Mage::helper('advanceseo/config')->isRewriteReview()){
			$reviewCollection 	= $urlrewriteModel->getCollection()->addFieldToFilter('target_path', array('like' => '%review%'));
			$dataView			= array(); 
			
			$reviewConllection = $model->getCollection()->addFieldToFilter('type', 'reviews');
			$reviewConllection->setPageSize((int)$this->_limitRecords);
			
			$advanceSeo = $advanceoSeoConllection->getFirstItem();			
			$advanceId 	= $advanceSeo->getId();
			$tagsId 	= $advanceSeo->getUrl();
				
			if($tagsId != NULL) {
				$reviewConllection->addFieldToFilter('url_rewrite_id', array('gt' => $tagsId));
			}
			
			if(count($reviewCollection)!=0){
				$modelProduct = Mage::getModel('catalog/product');	
				foreach($reviewCollection as $review){
					preg_match('/[0-9]+/', $review->getTargetPath(), $match);
					$productId 	= $match[0];
					$product	= $modelProduct->load($productId);
					$requestPath= Mage::helper('advanceseo/config')->getPathReview().'/'.
								  Mage::helper('advanceseo/data')->stringConvert($product->getName()).
								  Mage::helper('advanceseo/data')->getSuffix(); 
					if($this->_counter == $this->_limitRecords){
						break;
					}
					if($review->getRequestPath() != $requestPath){

						$dataView[] = $review->getId();
						$datacorereview['request_path'] = $requestPath;
						$urlrewriteModel->load($review->getId())->addData($datacorereview);
						$urlrewriteModel->setId($review->getId())->save();
						$this->_counter++;
					}	
				}
				$dataCore = array();
				$dataCore['type']='reviews';
				$dataCore['url'] = max($dataView);
				if(count($reviewConllection) != 0){

					$model->load($advanceId)->addData($dataCore);
					$model->save();
				}else{	
					$model->setData($dataCore);
					$model->save();
				}
				
			}
		}
	}
	
	public function rewriteData()
	{
		$this->_limitRecords = (int)Mage::helper('advanceseo/existeddata')->getNumberRecord();
		/*
		if(Mage::helper('advanceseo/existeddata')->isEnableRewriteUrl()){
			$this->rewriteUrl();
		}
		*/
		if(Mage::helper('advanceseo/existeddata')->isEnableRewriteMeta()){
			if(Mage::helper('advanceseo/meta')->isEnableMeta()){
				$this->rewriteMetaTag();
				
			}
		}
		return true;
	}
}
?>